const { ossService } = require('../services/oss.service');

/**
 * 获取文件上传签名URL
 */
const getUploadSignedUrl = async (req, res) => {
  try {
    const { dir, filename } = req.query;
    if (!dir) {
      return res.status(400).json({
        code: 400,
        message: '请提供目录名'
      });
    }
    if (!filename) {
      return res.status(400).json({
        code: 400,
        message: '请提供文件名'
      });
    }

    const result = await ossService.getUploadSignedUrl(dir, filename);
    return res.status(200).json({
      code: 200,
      data: result
    });
  } catch (error) {
    console.error('Failed to get upload signed URL:', error);
    if (error.code === 'NoSuchBucket') {
      return res.status(404).json({
        code: 404,
        message: 'OSS bucket不存在'
      });
    }
    return res.status(500).json({
      code: 500,
      message: '获取上传签名URL失败'
    });
  }
};

/**
 * 获取文件访问签名URL
 */
const getAccessSignedUrl = async (req, res) => {
  try {
    const { file_path } = req.query;
    if (!file_path) {
      return res.status(400).json({
        code: 400,
        message: '请提供文件路径'
      });
    }

    const signedUrl = await ossService.getAccessSignedUrl(file_path);
    return res.status(200).json({
      code: 200,
      data: {
        signedUrl
      }
    });
  } catch (error) {
    console.error('Failed to get access signed URL:', error);
    if (error.code === 'NoSuchBucket') {
      return res.status(404).json({
        code: 404,
        message: 'OSS bucket不存在'
      });
    }
    return res.status(500).json({
      code: 500,
      message: '获取访问签名URL失败'
    });
  }
};

/**
 * 删除文件
 */
const deleteFile = async (req, res) => {
  try {
    const { file_path } = req.body;
    if (!file_path) {
      return res.status(400).json({
        code: 400,
        message: '请提供文件路径'
      });
    }

    await ossService.deleteFile(file_path);
    return res.status(200).json({
      code: 200,
      message: '文件删除成功'
    });
  } catch (error) {
    console.error('Failed to delete file:', error);
    if (error.code === 'NoSuchBucket') {
      return res.status(404).json({
        code: 404,
        message: 'OSS bucket不存在'
      });
    }
    return res.status(500).json({
      code: 500,
      message: '删除文件失败'
    });
  }
};

module.exports = {
  getUploadSignedUrl,
  getAccessSignedUrl,
  deleteFile
}; 